
let Base = require('Base');
cc.macro.ENABLE_TRANSPARENT_CANVAS = true;
cc.Class({
    extends: Base,
    ctor(){
        this._gameStepTemp = {
            aniTime: 0.5,
            delay: 2,
            callFn: 'callEnd', 
            startY: -60,
            step: 50,
            minH: 100,
            areas: []
        }
        this._gameStepBase = [
            {
                aniTime: 0.5,
                delay: 2,
                callFn: 'callEnd', 
                startY: -60,
                step: 50,
                minH: 100,
                areas: [
                    'xxxxxxxxxxxxxxxxxxx',
                    'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
                    'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
                ]
            }
        ];
        this._gameStep = [];  

        //视频列表
        this._videoList = [];
        //当前播放视频的索引
        this._curVideoIndex = 0;
        //当前视频链接
        this._videoUrl = '';

        this.curStep = 0;
        

        //游戏状态：ready, start, over
        this.gameState = 'ready';
        //游戏进行时间
        this._startTime = 0;
        //帧速率 60帧/s
        this.FPS = 60;
        //视频 ready
        this.videoLoadReady = false;
        //是否点击了开始
        this.isClickStart = false;
        
        //是否添加了控件条
        this.isAddControl = false;
        //游戏是否暂停
        this.pause = false;
        this.pauseTimer = null;

        //初始总喜乐豆
        this._totalXLbean = 0;
        //游戏过程中获得得喜乐豆
        this._getXLbean = 0;
        //钻石卡
        this._diamondCardNum = 0;
        //黄金卡
        this._goldCardNum = 0;
        //延迟执行得函数
        this._delayFn = null;
    },
    properties: {
        //是否是倒计时
        isCountDown: {
            type: Boolean,
            default: false,
        },
        //游戏时间（倒计时）
        gameTime: {
            type: Number,
            default: 30,
        },
        //游戏得分
        score: {
            type: Number,
            default: 0,
        },        
        ledouBox: cc.Node,
        pubb: cc.Prefab,
        pubb2: cc.Prefab,        
        //本局游戏中获得得喜乐豆
        getXLbean: {
            get: function(){
                return this._getXLbean
            },
            set: function(val){
                this._getXLbean = val;
                this.commTopNode.emit('updateNum', {
                    dou2: String(this._getXLbean),
                })                  
            }
        },
        //喜乐豆
        totalXLbean: {
            get: function(){
                return this._totalXLbean
            },
            set: function(val){
                this._totalXLbean = val;
                this.commTopNode.emit('updateNum', {
                    dou: String(this._totalXLbean),
                })  
            }
        },  
        //钻石卡
        diamondCardNum: {
            get: function(){
                return this._diamondCardNum
            },
            set: function(val){
                this._diamondCardNum = val;
                this.commTopNode.emit('updateNum', {
                    zuanka: String(this._diamondCardNum)
                })  
            }
        },     
        //金卡
        diamondCardNum: {
            get: function(){
                return this._goldCardNum
            },
            set: function(val){
                this._goldCardNum = val;
                this.commTopNode.emit('updateNum', {
                    jinka: String(this._goldCardNum)
                })  
            }
        },                   
        //游戏时间
        startTime: {
            get: function(){
                return this._startTime
            },
            set: function(val){
                this._startTime = val;
                //倒计时
                if(this.isCountDown){
                    this.commTopNode.emit('updateNum', {
                        time: Math.floor(this.gameTime - this._startTime)
                    })  
                //正计时  
                }else{
                    this.commTopNode.emit('updateNum', {
                        time: Math.floor(this._startTime)
                    })
                }
            }
        }
    },
    _onLoad () {
        //获取节点
        this._initNode()
        //绑定事件
        this._initBindEvent()

        this.getConf().then(res=>{
            let resConf = res.data.data.gameInfo.gameConfig;

            this.todayCanGetXileBean = res.data.todayCanGetXileBean;
            //喜乐豆
            this.totalXLbean = res.data.userXileBean;
            //钻石卡
            this.diamondCardNum = res.data.diamondCardNum;
            //黄金卡
            this.goldCardNum = res.data.goldCardNum;            
            // this._delayFn = function(){
            //     //喜乐豆
            //     this.totalXLbean = res.data.userXileBean;
            //     //钻石卡
            //     this.diamondCardNum = res.data.diamondCardNum;
            //     //黄金卡
            //     this.goldCardNum = res.data.goldCardNum;
            // }
            //this._initConfig(resConf)
            //this.startBtn.on('touchstart', this._clickStart, this)
        }).catch(err=>{
            console.log(err);
            //this.gameBefore.emit('init', this._gameStepBase);
            //this.startBtn.on('touchstart', this._clickStart, this)
        })

        setTimeout(()=>{
            this.commTopNode.emit('renderFaceList', {
                list: [1, 2, 3, 4, 5, 6]
            });
        }, 0)

        this.startBtn.on('touchstart', this._timerEnd, this)

        // this.timerNode.active = true;
        // this.timerNodeAni.play();

    },
    _initConfig(resConf){
        //初始化自定义配置
        this.initCustomConfig && this.initCustomConfig(resConf)

        //console.log(resConf)
        let date = this.getQS('nowTime') || this.getCurDate();
        this._videoList = resConf.hs_configs;
        let hsConfList = resConf.hs_configs;
        
        let curIndex = 0;
        hsConfList = hsConfList.filter((item, index)=>{
            if(item.date == date){
                curIndex = index;
                return true;
                
            }else{
                return false;
            }
        })
        if(hsConfList.length == 0){
            hsConfList.push(resConf.hs_configs[0])
            curIndex = 0;
        }
        this._curVideoIndex = curIndex;
        let curConf = hsConfList[0];
        let obj = JSON.parse(JSON.stringify(this._gameStepTemp))
        for(let name in curConf){
            if(/^hs/.test(name)){
                obj.areas.push(curConf[name])
            }
        }
        this._gameStep.push(obj)
        this.gameBefore.emit('init', this._gameStep);

        this._videoUrl = curConf.video_url;
        if(this._videoUrl){
            this._loadVideo()
        }
    },
    //加载并播放视频
    _loadVideo(){
        cc.assetManager.loadRemote(this._videoUrl, (err, videoClip) =>{
            if(err){
                console.log(err);
                return false;
            }
            this.playerComp.clip = videoClip;    
            this.bgVideo.on('meta-loaded', ()=>{
                console.log('meta-loaded')
                this.videoLoadReady = true;
                this._addVideoControl();
                if(this.isClickStart){
                    this.playBgVideo(this.playerComp)
                }
            })
        });
    },    
    //添加视频控件条
    _addVideoControl(){
        if(this.isAddControl){
            return false
        }
        cc.resources.load("prefab/control", (err, prefab)=>{
            let control = cc.instantiate(prefab);
            let controlWidget = control.getComponent(cc.Widget);
            controlWidget.target = this.canvas;
            this.canvas.insertChild(control, this.startScene.getSiblingIndex()-1);
            this.isAddControl = true;
        });
    },    
    /*
        重置视频播放进度
        videoPlayerComp: [cc.VideoPlayer]
    */
    resetBgVideoCurTime(videoPlayerComp){
        let videoObj = videoPlayerComp._impl._video;
        videoObj.currentTime = 0; 
        videoObj.play() 
    },
    //播放下一条视频
    playNextVideo(){
        console.log('playNextVideo')
        this._curVideoIndex++;
        let cur = this._videoList[this._curVideoIndex];
        if(!cur){
            this.curVideoIndex = 0;
            cur = this.videoList[0];
        }

        this._videoUrl = cur.video_url;
        this._loadVideo();
        setTimeout(()=>{
            this.playBgVideo(this.playerComp)
        }, 30)
    },    
    /*
        播放视频
        videoPlayerComp: [cc.VideoPlayer]
    */
    playBgVideo(videoPlayerComp){
        let videoObj = videoPlayerComp._impl._video;
        videoObj.play();
        setTimeout(()=>{
            videoObj.pause();
            setTimeout(()=>{
                videoObj.play();
                videoObj.muted = false;
                videoPlayerComp.mute = false;                
            },30)            
        },30)
    },    
    createScoreNode(curPos, num){
        if(curPos instanceof cc.Node){
            curPos = curPos.convertToWorldSpaceAR(cc.v2(0,0))
        }
        let pubb = cc.instantiate(num<0?this.pubb:this.pubb2);
        let label = pubb.children[0].getComponent(cc.Label);
        label.string = num>0?'+'+num:String(num);
        let disPos = curPos.sub(this.ledouBox.convertToWorldSpaceAR(cc.v2(0,0)));
        pubb.setPosition(disPos)
        this.ledouBox.addChild(pubb)
        cc.tween(pubb).bezierTo(2, cc.v2(disPos.x, disPos.y*2/3), cc.v2(0, disPos.y*1/3), cc.v2(0,0)).call(()=>{
            pubb.destroy();
        }).start()
    },    
    //点击继续游戏
    _clickRestartGame(){
        // cc.tween(this.gameAfterNode)
        //     .by(1, {position: cc.v2(750, 0)})
        //     .start();
        this.startBtn.active = true;
        // this.timerNode.active = true;
        // this.gameBox.active = true;
        // this.timerNodeAni.play();
        // this.gameStartNode.active = true;

        //this.resetBgVideoCurTime(this.playerComp);
        //播放下一条视频
        //this.playNextVideo();
        this.clickRestartBtn && this.clickRestartBtn();
        this._resetGame();
    },    
    //点击开始游戏
    _clickStart(){
        this.isClickStart = true;
        this.startScene.active = false;
        
        this.timerNode.active = true;
        this.timerNodeAni.play();
        this.gameBox.active = true;
        this.gameStartNode.active = true;

        if(this._delayFn){
            this._delayFn.call(this)
            this._delayFn = null;
        }
        this.hsPlayEnd && this.hsPlayEnd()

        //this.playBeforeArea();
        // if(this.videoLoadReady){
        //     this.playBgVideo(this.playerComp)
        // }
        // this.playBgVideo(this.playerComp)

        // setTimeout(()=>{
        //     this._addVideoControl();
        // }, 100)

        this.clickStart && this.clickStart();
    },
    //播放消息气泡
    playBeforeArea(){
        this.gameBefore.emit('play', {
            index: this.curStep,
        })
        this.curStep++;
    },

    //暂停游戏
    _pauseGameFn(){
        if(this.pauseTimer){
            return false;
        }
        //打开
        if(this.pause){
            if(this.gameState == 'over'){
                this.gameAfterNode.active = true;
                this.pauseTimer = null;
                this.pause = !this.pause;
                this.openGame && this.openGame();
            }else{
                this.timerNode2.active = true;
                this.timerNodeAni2.play();                
                this.pauseTimer = setTimeout(()=>{
                    this.gameBox.active = true;
                    //隐藏
                    this.pauseGameAni.play('pauseAni - 001')
                    this.pause = !this.pause;
                    clearTimeout(this.pauseTimer)
                    this.pauseTimer = null;
                    this.openGame && this.openGame();
                }, 3000)
            }
        //隐藏
        }else{
            //打开
            this.pauseGameAni.play('pauseAni')
            this.gameBox.active = false;
            this.pause = !this.pause;
            if(this.gameState == 'over'){
                this.gameAfterNode.active = false;
            }
            this.hideGame && this.hideGame();
        }
    },
    //开始游戏
    _startGame(){
        
        this.gameState = 'start';
        this.startGame && this.startGame();
    },
    //重置游戏
    _resetGame(){
        this.startTime = 0;
        this.score = 0;
        this.resetGame && this.resetGame();
    },
    //游戏结束
    _gameOver(){
        this.gameState = 'over';
        //this.scoreNumLabel.string = '获得喜乐豆：'+this.getXLbean;
        //this.scoreNumLabel.string = '得分：'+this.score;
        this.gameOverLayer.active = true;
        this.gameOverLayer.emit('gameover', { 
            score: this.score,
            bean: this.getXLbean,
            card: {
                text: '金卡',
                num: 0
            }
        })
        
        //游戏结束 更新总乐豆数
        this.totalXLbean+=this.getXLbean;
        this.submitScore(this.score, ()=>{
            this.submitCallBack && this.submitCallBack()
        })
        // this.submitScoreV2(this.score, this.getXLbean, ()=>{
        //     this.submitCallBack && this.submitCallBack()
        // })
        //重重获得乐豆的数量
        this.getXLbean = 0;

        this.gameOver && this.gameOver();
    },
    //游戏结束，从外面调用
    callGameOver(){
        this._gameOver();
    },    
    //倒计时结束
    _timerEnd(){
        //this.pauseGameBtn.active = true;        
        this.timerNode.active = false; 
        this.gameStartNode.active = false;
        this.startBtn.active = false;
        this._startGame();
    },    
    //绑定事件
    _initBindEvent(){
        //开始游戏按钮
        //this.startBtn.on('touchstart', this._clickStart, this)
        //倒计时
        this.canvas.on('timerEnd', this._timerEnd, this);
        //消息气泡播放结束
        this.canvas.on('areaPlayEnd', (i)=>{
            
            this.timerNode.active = true;
            this.timerNodeAni.play();
            this.gameBox.active = true;
            this.gameStartNode.active = true;

            if(this._delayFn){
                this._delayFn.call(this)
                this._delayFn = null;
            }
            this.hsPlayEnd && this.hsPlayEnd()
        })
        console.log(this.gameOverLayer)
        this.gameOverLayer.on('close', ()=>{
            this._clickRestartGame();
        })

        this.gameOverLayer.on('restart', ()=>{
            this._clickRestartGame();    
            this._timerEnd();        
        })        
        //继续游戏
        // this.restartBtn.on('touchstart', this._clickRestartGame, this);

        // //返回列表
        // this.backListBtn.on('touchstart', this._backList, this);
    },    
    //获取节点
    _initNode(){
        this.canvas = cc.find('Canvas');
        //游戏主场景 节点
        this.gameBox = cc.find('Canvas/gameBox');
        //this.gameBox.active = false;  
        //消息气泡节点
        this.gameBefore = cc.find('Canvas/gameBefore');
        //公用计分组件
        this.commTopNode = cc.find('Canvas/gameBox/commTop');
        //开始游戏提示
        this.gameStartNode = cc.find('Canvas/startGame');
        //开始游戏 倒计时
        this.timerNode = cc.find('Canvas/timer');
        //倒计时动画组件
        this.timerNodeAni = this.timerNode.getComponent(cc.Animation);  
        //游戏初始场景节点
        this.startScene = cc.find('Canvas/startScene');
        //开始按钮
        this.startBtn = cc.find('Canvas/startGame/startBtn');

        //游戏结束弹层
        this.gameOverLayer = cc.find('Canvas/gameOverLayer');

    }, 
    _update (dt) {
        this.FPS = Math.floor(1/dt);

        if(this.pause){
            return false;
        }

        if(this.gameState != 'start'){
            return false;
        }
        this.startTime+=dt;
        //倒计时
        if(this.isCountDown){
            if(this.startTime >= this.gameTime){
                this.startTime = 0;
                this._gameOver();
            }     
        }
    },
});
